package com.zhoutian.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zhoutian.dao.RoleDao;
import com.zhoutian.entity.PageResult;
import com.zhoutian.entity.QueryPageBean;
import com.zhoutian.pojo.Role;
import com.zhoutian.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色服务
 */
@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;


    //建立角色和权限多对多关系
    public void setRoleAndPermission(Integer roleId, Integer[] permissionIds){
        if(permissionIds != null && permissionIds.length > 0){
            for (Integer permissionId : permissionIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("roleId",roleId);
                map.put("permissionId",permissionId);
                roleDao.setRoleAndPermission(map);
            }
        }
    }

    //新增角色，同时需要让角色关联权限
    @Override
    public void add(Role role, Integer[] permissionIds) {
        //新增角色
        roleDao.add(role);
        //设置角色和权限的多对多的关联关系
        Integer roleId = role.getId();
        this.setRoleAndPermission(roleId,permissionIds);
    }

    //分页查询
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<Role> page = roleDao.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    //编辑角色信息，同时需要关联权限
    @Override
    public void edit(Role role, Integer[] permissionIds) {
        //修改角色基本信息
        roleDao.edit(role);
        //清理当前角色关联的权限
        roleDao.deleteAssocication(role.getId());
        //重新建立当前角色和权限的关联关系
        Integer roleId = role.getId();
        this.setRoleAndPermission(roleId,permissionIds);
    }

    //根据ID删除角色
    @Override
    public void deleteById(Integer id) {
        //判断当前角色是否已经关联到用户
        long count = roleDao.findCountByRoleId(id);
        if(count > 0){
            //当前角色已经被关联到用户，不允许删除
            new RuntimeException();
        }
        roleDao.deleteAssocication(id);
        roleDao.deleteRoleById(id);
    }

    //根据角色ID查询关联的权限ID
    @Override
    public List<Integer> findPermissionIdsByRoleId(Integer id) {
        return roleDao.findPermissionIdsByRoleId(id);
    }

    //根据ID查询检查组
    @Override
    public Role findById(Integer id) {
        return roleDao.findById(id);
    }

    @Override
    public List<Role> findAll(){
        return roleDao.findAll();
    }

}
